package cn.baage.campus.utils;

import cn.baage.campus.config.properties.BaageProperties;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * @Description: 邮件工具
 * @Author: 八阿哥
 * @url: baage.cn
 * @Version: 1.0
 **/
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Slf4j
public class MailUtils {

    private final BaageProperties baageProperties;
    private final JavaMailSender mailSender;


    private final ExecutorService executorService = new ThreadPoolExecutor(
            Runtime.getRuntime().availableProcessors(),
            Runtime.getRuntime().availableProcessors() * 2, 60, TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(1000));

    /**
     * 发送邮箱验证码
     * @param to  收件人(多个时参数形式: "xxx@xxx.com,xxx@xxx.com")
     * @param code 验证码
     */
    public void sendCode(String to, String code) {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper;
        String content = getContent(code);
        try {
            messageHelper = new MimeMessageHelper(message, true);
            //邮件发送人
            messageHelper.setFrom(baageProperties.getMailFrom());
            //邮件接收人,设置多个收件人地址
            InternetAddress[] internetAddressTo = InternetAddress.parse(to);
            messageHelper.setTo(internetAddressTo);
            //messageHelper.setTo(to);
            //邮件主题
            message.setSubject("Baage校园圈-验证码");
            //邮件内容，html格式
            messageHelper.setText(content, true);
            //发送
            executorService.submit(() -> mailSender.send(message));
            //日志信息
            log.info("邮件验证码成功发送：{}", code);
        } catch (Exception e) {
            log.error("发送邮件验证码时发生异常，异常信息：{}", e.getMessage());
        }
    }


    /**
     * 获取验证码模板
     *
     * @param code 验证码
     * @return 验证码模板
     */
    private String getContent(String code) {
        //加载邮件html模板
        Resource resource = new ClassPathResource("mail-template.ftl");
        StringBuilder buffer = new StringBuilder();
        String line;
        try(
                InputStream inputStream = resource.getInputStream();
                BufferedReader fileReader = new BufferedReader(new InputStreamReader(inputStream));
        ) {
            while ((line = fileReader.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            log.info("发送邮件读取模板失败{}", e.getMessage());
        }
        //替换html模板中的参数
        return MessageFormat.format(buffer.toString(), code);
    }

}
